package com.example.autopia.view.Adapters

import android.provider.ContactsContract.Contacts.Photo
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.autopia.R
import com.example.autopia.databinding.ViewholderNewsHotnewsImageBinding
import com.example.autopia.model.Item.HotNews
import com.example.autopia.utilities.ImageManager
import com.example.autopia.view.Listeners.HotNewsListener

class HotNewsAdapter  :
    RecyclerView.Adapter<HotNewsAdapter.ViewHolder>() {

    private lateinit var list : MutableList<HotNews>
    private lateinit var listener: HotNewsListener

    fun attachListener(listener: HotNewsListener) {
        this.listener = listener
    }
    fun setData(newList : List<HotNews>){
        list = newList.toMutableList()
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = ViewholderNewsHotnewsImageBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val news = list[position]
        holder.bind(news,listener)
    }

    override fun getItemCount(): Int {
        return list.size
    }

    inner class ViewHolder(private val binding: ViewholderNewsHotnewsImageBinding) :
        RecyclerView.ViewHolder(binding.root) {
        private val imageManager = ImageManager()
        fun bind(hotNews: HotNews,listener: HotNewsListener) {
            binding.tvTitle.text = hotNews.title
            Glide.with(itemView)
                .load(imageManager.byteArrayToBitmap(hotNews.photo))
                .centerCrop()
                .placeholder(R.drawable.hotnews_placeholder)
                .error(R.drawable.hotnews_placeholder)
                .into(binding.Photo)
            binding.root.setOnClickListener {
                listener.onNewsClick(hotNews)
            }
        }
    }
}